package com.twu.biblioteca;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class BibliotecaApp {

    private Library library;

    public static void main(String[] args) throws Exception {
        BibliotecaApp app = new BibliotecaApp();
        app.run();
    }

    private void run() throws IOException {

        library = new Library("Biblioteca");
        library.addBook(new Book(1, "The Pragmatic Programmer"));
        library.addBook(new Book(2, "Test Driven Development"));
        library.addBook(new Book(3, "HeadFirst Java"));
        library.addBook(new Book(4, "An Ordinary Person's Guide to Empire"));
        library.addBook(new Book(5, "Go Kiss the World"));
        library.addBook(new Book(6, "Oh! the places you'll go"));

        System.out.println("Welcome! Biblioteca is now available for use.");

        while (true) {

            displayMenu();

            int choice = acceptUserInput();
            switch (choice) {
                case 1:
                    displayBooks();
                    break;
                case 2:
                    checkOutBook();
                    break;
                case 3:
                    returnBook();
                    break;
                case 4:
                    System.exit(0);
                    break;
                default:
                    System.out.println("Select a valid option!");
            }
        }
    }

    private void returnBook() throws IOException {
        System.out.println("Please enter the book id:");
        int bookId = acceptUserInput();
        if (library.returnBook(bookId)) {
            System.out.println("Thanks for returning the book");
        } else {
            System.out.println("That is not a valid book to return.");
        }
    }

    private void displayBooks() {
        library.displayBooks();
    }

    private int acceptUserInput() throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        return Integer.parseInt(br.readLine());
    }

    private void checkOutBook() throws IOException {
        System.out.println("Please enter the book id:");
        int bookId = acceptUserInput();
        if (library.checkOutBook(bookId)) {
            System.out.println("Thank you! Enjoy the book");
        } else {
            System.out.println("That book is not available.");
        }
    }


    public void displayMenu() {
        System.out.println("\nMain menu:-");
        System.out.println("1. View list of all books");
        System.out.println("2. Check-out a book");
        System.out.println("3. Return a book");
        System.out.println("4. Exit");
        System.out.println("Please pick a choice(1-4):");
    }
}
